package com.uzai.console.service.zombiefan.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.uzai.console.common.utils.DateUtil;
import com.uzai.console.common.utils.Tools;
import com.uzai.console.dto.wechatprivate.wxcontacts.WxContactsQuery;
import com.uzai.console.dto.wechatwork.wxworkcontacts.WxworkContactsQuery;
import com.uzai.console.dto.zombiefan.zombiefantask.ZombieFanTaskDto;
import com.uzai.console.entity.ZombieFanTask;
import com.uzai.console.entity.ZombieFanTaskSendInfo;
import com.uzai.console.entity.es.EsWxContacts;
import com.uzai.console.enums.ZombieFanTaskStatusEnum;
import com.uzai.console.mapper.DeviceWechatInfoMapper;
import com.uzai.console.mapper.DeviceWxworkInfoMapper;
import com.uzai.console.mapper.ZombieFanTaskMapper;
import com.uzai.console.mapper.ZombieFanTaskSendInfoMapper;
import com.uzai.console.service.device.DeviceService;
import com.uzai.console.service.wechatprivate.WxContactsService;
import com.uzai.console.service.wechatwork.WxworkContactsService;
import com.uzai.console.service.zombiefan.ZombieFanTaskSyncService;
import com.uzai.console.vo.wechatwork.wxworkcontacts.WxworkContactsVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 清理僵尸粉任务
 * @author liuqi
 * @date 2021年08月13日 11:34
 */
@Service
public class ZombieFanTaskSyncServiceImpl implements ZombieFanTaskSyncService {

    Logger logger = LoggerFactory.getLogger(ZombieFanTaskSyncServiceImpl.class);

    @Autowired
    private ZombieFanTaskMapper zombieFanTaskMapper;
    @Autowired
    private ZombieFanTaskSendInfoMapper zombieFanTaskSendInfoMapper;
    @Autowired
    private DeviceService deviceService;
    @Autowired
    private DeviceWechatInfoMapper deviceWechatInfoMapper;
    @Autowired
    private DeviceWxworkInfoMapper deviceWxworkInfoMapper;
    @Autowired
    private WxContactsService wxContactsService;
    @Autowired
    private WxworkContactsService wxworkContactsService;

    /**
     * 后台异步添加个人微信机器人清理僵尸粉任务
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param zombieFanTaskDto
     * @return null
     */
    @Async("taskExecutor")
    public void addZombieFanTaskByWechat(ZombieFanTaskDto zombieFanTaskDto){
        List<Long> deviceUniqueIdList = zombieFanTaskDto.getDeviceUniqueIdList();
        if(deviceUniqueIdList != null && deviceUniqueIdList.size() > 0){
            for (Long deviceUniqueId : deviceUniqueIdList) {

                ZombieFanTask zombieFanTask_old = zombieFanTaskMapper.selectByDeviceUniqueId(deviceUniqueId, zombieFanTaskDto.getMerId());
                if(zombieFanTask_old != null){
                    continue;
                }

                int now = DateUtil.getNowTime();
                //保存清粉任务
                ZombieFanTask zombieFanTask = new ZombieFanTask();
                zombieFanTask.setId(IdWorker.getId());
                zombieFanTask.setName(zombieFanTaskDto.getName());
                zombieFanTask.setMerId(zombieFanTaskDto.getMerId());
                zombieFanTask.setDeviceType(zombieFanTaskDto.getDeviceType());
                zombieFanTask.setDeviceUniqueId(deviceUniqueId);
                zombieFanTask.setQueryRemark(Tools.getStrNull(JSONArray.toJSONString(zombieFanTaskDto.getQueryRemarkList())));
                zombieFanTask.setStatus(ZombieFanTaskStatusEnum.INIT.getId());
                zombieFanTask.setCheckMin(zombieFanTaskDto.getCheckMin());
                zombieFanTask.setCheckMax(zombieFanTaskDto.getCheckMax());
                zombieFanTask.setZombieRemark(zombieFanTaskDto.getZombieRemark());
                zombieFanTask.setDelMin(zombieFanTaskDto.getDelMin());
                zombieFanTask.setDelMax(zombieFanTaskDto.getDelMax());
                zombieFanTask.setDelDayLimit(zombieFanTaskDto.getDelDayLimit());
                zombieFanTask.setTotalNum(0);
                zombieFanTask.setCheckTime(0);
                zombieFanTask.setCheckNum(0);
                zombieFanTask.setDelTime(0);
                zombieFanTask.setDelDayNum(0);
                zombieFanTask.setCheckType(Tools.getInteger(zombieFanTaskDto.getCheckType()));
                zombieFanTask.setCheckMsg(zombieFanTaskDto.getCheckMsg());
                zombieFanTask.setDelUser(Tools.getInteger(zombieFanTaskDto.getDelUser()));
                zombieFanTask.setDelUserRemark(zombieFanTaskDto.getDelUserRemark());
                zombieFanTask.setDelUserStatus(0); //默认0
                zombieFanTask.setCreateTime(now);
                zombieFanTask.setUpdateTime(now);
                zombieFanTaskMapper.insert(zombieFanTask);
                //调用单个个人微信机器人的通讯录信息全部保存到清粉任务明细当中
                WxContactsQuery wxContactsQuery = new WxContactsQuery();
                wxContactsQuery.setMerId(zombieFanTaskDto.getMerId());
                wxContactsQuery.setDeviceUniqueId(deviceUniqueId);
                wxContactsQuery.setUserType(0); //个人微信通讯录
                wxContactsQuery.setRemarkList(zombieFanTaskDto.getQueryRemarkList());
                //执行分页查询对象
                wxContactsQuery.setSize(10);
                int currentPage = 1;
                wxContactsQuery.setCurrent(currentPage);
                //批量保存文件对象(100条一次)
                List<ZombieFanTaskSendInfo> zombieFanTaskSendInfoList = new ArrayList<>();
                //查询总数
                Page<EsWxContacts> wxContactsList = wxContactsService.findWxContactsListForGroupSendMsg(wxContactsQuery);
                //修改检查总数
                if(wxContactsList != null && wxContactsList.getTotal() > 0){
                    zombieFanTask.setTotalNum((int) wxContactsList.getTotal());
                    zombieFanTaskMapper.updateById(zombieFanTask);
                }

                try {
                    while(wxContactsList != null && wxContactsList.getRecords() != null && wxContactsList.getRecords().size() > 0){

                        for(EsWxContacts wxContactsInfoVo : wxContactsList.getRecords()){
                            if(StringUtils.isNotBlank(wxContactsInfoVo.getWxid()) && wxContactsInfoVo.getWxid().length() < 50){
                                ZombieFanTaskSendInfo zombieFanTaskSendInfo = new ZombieFanTaskSendInfo();
                                zombieFanTaskSendInfo.setId(IdWorker.getId());
                                zombieFanTaskSendInfo.setMerId(zombieFanTaskDto.getMerId());
                                zombieFanTaskSendInfo.setTaskId(zombieFanTask.getId());
                                zombieFanTaskSendInfo.setDeviceType(zombieFanTaskDto.getDeviceType());
                                zombieFanTaskSendInfo.setDeviceUniqueId(deviceUniqueId);
                                zombieFanTaskSendInfo.setWxid(wxContactsInfoVo.getWxid());
                                zombieFanTaskSendInfo.setNick(wxContactsInfoVo.getNick());
                                zombieFanTaskSendInfo.setCheckTime(0);
                                zombieFanTaskSendInfo.setCreateTime(now);
                                zombieFanTaskSendInfo.setUpdateTime(now);
                                zombieFanTaskSendInfoList.add(zombieFanTaskSendInfo);

                                //判断条数，如果条数大于50条，批量处理
                                if(zombieFanTaskSendInfoList.size() >= 50){
                                    //批量保存清理僵尸粉发送明细
                                    zombieFanTaskSendInfoMapper.batchAdd(zombieFanTaskSendInfoList);
                                    //清空数据列表
                                    zombieFanTaskSendInfoList.clear();
                                }
                            }else{
                                logger.error("添加清理僵尸粉任务-通讯录wxid错误的数据，id={}", wxContactsInfoVo.getId());
                            }
                        }

                        //循环查询下一页
                        currentPage ++ ;
                        wxContactsQuery.setCurrent(currentPage);
                        wxContactsList = wxContactsService.findWxContactsListForGroupSendMsg(wxContactsQuery);
                    }
                }catch (Exception e){
                    logger.error("添加清理僵尸粉任务初始化失败，error={}",e.getMessage());
                    logger.error(e.getMessage(), e);
                }

                //最后将剩余不足100条的记录，批量处理
                if(zombieFanTaskSendInfoList.size() > 0){
                    //批量保存清理僵尸粉发送明细
                    zombieFanTaskSendInfoMapper.batchAdd(zombieFanTaskSendInfoList);
                    //清空本次导出的数据列表
                    zombieFanTaskSendInfoList.clear();
                }

                //将任务状态修改成未开始
                zombieFanTask.setStatus(ZombieFanTaskStatusEnum.NO_START.getId());
                zombieFanTaskMapper.updateById(zombieFanTask);
            }
        }
    }

    /**
     * 后台异步添加企业微信机器人清理僵尸粉任务
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param zombieFanTaskDto
     * @return null
     */
    @Async("taskExecutor")
    public void addZombieFanTaskByWxwork(ZombieFanTaskDto zombieFanTaskDto){
        List<Long> deviceUniqueIdList = zombieFanTaskDto.getDeviceUniqueIdList();
        if(deviceUniqueIdList != null && deviceUniqueIdList.size() > 0){
            for (Long deviceUniqueId : deviceUniqueIdList) {

                ZombieFanTask zombieFanTask_old = zombieFanTaskMapper.selectByDeviceUniqueId(deviceUniqueId, zombieFanTaskDto.getMerId());
                if(zombieFanTask_old != null){
                    continue;
                }

                int now = DateUtil.getNowTime();
                //保存清粉任务
                ZombieFanTask zombieFanTask = new ZombieFanTask();
                zombieFanTask.setId(IdWorker.getId());
                zombieFanTask.setName(zombieFanTaskDto.getName());
                zombieFanTask.setMerId(zombieFanTaskDto.getMerId());
                zombieFanTask.setDeviceType(zombieFanTaskDto.getDeviceType());
                zombieFanTask.setDeviceUniqueId(deviceUniqueId);
                zombieFanTask.setQueryRemark(Tools.getStrNull(JSONObject.toJSONString(zombieFanTaskDto.getQueryRemarkList())));
                zombieFanTask.setStatus(ZombieFanTaskStatusEnum.INIT.getId());
                zombieFanTask.setCheckMin(Tools.getInteger(zombieFanTaskDto.getCheckMin()));
                zombieFanTask.setCheckMax(Tools.getInteger(zombieFanTaskDto.getCheckMax()));
                zombieFanTask.setZombieRemark(zombieFanTaskDto.getZombieRemark());
                zombieFanTask.setDelMin(zombieFanTaskDto.getDelMin());
                zombieFanTask.setDelMax(zombieFanTaskDto.getDelMax());
                zombieFanTask.setDelDayLimit(zombieFanTaskDto.getDelDayLimit());
                zombieFanTask.setTotalNum(0);
                zombieFanTask.setCheckTime(0);
                zombieFanTask.setCheckNum(0);
                zombieFanTask.setDelTime(0);
                zombieFanTask.setDelDayNum(0);
                zombieFanTask.setCheckType(Tools.getInteger(zombieFanTaskDto.getCheckType()));
                zombieFanTask.setCheckMsg(zombieFanTaskDto.getCheckMsg());
                zombieFanTask.setDelUser(Tools.getInteger(zombieFanTaskDto.getDelUser()));
                zombieFanTask.setDelUserRemark(zombieFanTaskDto.getDelUserRemark());
                zombieFanTask.setDelUserStatus(0); //默认未删除
                zombieFanTask.setCreateTime(now);
                zombieFanTask.setUpdateTime(now);
                zombieFanTaskMapper.insert(zombieFanTask);

                //调用单个企业微信机器人的通讯录信息全部保存到清粉任务明细当中
                //执行分页查询对象
                WxworkContactsQuery wxworkContactsQuery = new WxworkContactsQuery();
                wxworkContactsQuery.setMerId(zombieFanTaskDto.getMerId());
                wxworkContactsQuery.setDeviceUniqueId(deviceUniqueId);
                wxworkContactsQuery.setRemarkList(zombieFanTaskDto.getQueryRemarkList());
                wxworkContactsQuery.setSize(10);
                int currentPage = 1;
                wxworkContactsQuery.setCurrent(currentPage);
                //批量保存文件对象(100条一次)
                List<ZombieFanTaskSendInfo> zombieFanTaskSendInfoList = new ArrayList<>();
                //查询通讯录
                Page<WxworkContactsVo> wxworkContactsVoList = wxworkContactsService.findWxworkContactsList(wxworkContactsQuery, false);
                //修改检查总数
                if(wxworkContactsVoList != null && wxworkContactsVoList.getTotal() > 0){
                    zombieFanTask.setTotalNum((int) wxworkContactsVoList.getTotal());
                    zombieFanTaskMapper.updateById(zombieFanTask);
                }
//
//                while(wxworkContactsVoList != null && wxworkContactsVoList.getRecords() != null && wxworkContactsVoList.getRecords().size() > 0) {
//                    for (WxworkContactsVo wxworkContactsVo : wxworkContactsVoList.getRecords()) {
//                        ZombieFanTaskSendInfo zombieFanTaskSendInfo = new ZombieFanTaskSendInfo();
//                        zombieFanTaskSendInfo.setId(IdWorker.getId());
//                        zombieFanTaskSendInfo.setMerId(zombieFanTaskDto.getMerId());
//                        zombieFanTaskSendInfo.setTaskId(zombieFanTask.getId());
//                        zombieFanTaskSendInfo.setDeviceType(zombieFanTaskDto.getDeviceType());
//                        zombieFanTaskSendInfo.setDeviceUniqueId(deviceUniqueId);
//                        zombieFanTaskSendInfo.setWxid(wxworkContactsVo.getWxid());
//                        zombieFanTaskSendInfo.setNick(wxworkContactsVo.getUserName());
//                        zombieFanTaskSendInfo.setCheckTime(0);
//                        zombieFanTaskSendInfo.setCreateTime(now);
//                        zombieFanTaskSendInfo.setUpdateTime(now);
//                        zombieFanTaskSendInfoList.add(zombieFanTaskSendInfo);
//
//                        //判断条数，如果条数大于100条，批量处理
//                        if(zombieFanTaskSendInfoList.size() >= 100){
//                            //批量保存清理僵尸粉发送明细
//                            zombieFanTaskSendInfoMapper.batchAdd(zombieFanTaskSendInfoList);
//                            //清空数据列表
//                            zombieFanTaskSendInfoList.clear();
//                        }
//                    }
//
//                    //循环查询下一页
//                    currentPage ++ ;
//                    wxworkContactsQuery.setCurrent(currentPage);
//                    wxworkContactsVoList = wxworkContactsService.findWxworkContactsList(wxworkContactsQuery,false);
//                }
//
//                //最后将剩余不足100条的记录，批量处理
//                if(zombieFanTaskSendInfoList.size() > 0){
//                    //批量保存清理僵尸粉发送明细
//                    zombieFanTaskSendInfoMapper.batchAdd(zombieFanTaskSendInfoList);
//                    //清空本次导出的数据列表
//                    zombieFanTaskSendInfoList.clear();
//                }

                //将任务状态修改成未开始
                zombieFanTask.setStatus(ZombieFanTaskStatusEnum.NO_START.getId());
                zombieFanTaskMapper.updateById(zombieFanTask);
            }
        }
    }


}
